package hjw.com.controller;

import hjw.com.entity.Cart;
import hjw.com.entity.User;
import hjw.com.service.CartServiceImpl;
import hjw.com.service.UserServiceImpl;
import hjw.com.util.PackJsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Project:Academic - CartController
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/2/17 16:12
 * @since 1.8
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final CartServiceImpl cartDao;
    private final UserServiceImpl userDao;

    @Autowired
    public CartController(CartServiceImpl cartDao, UserServiceImpl userDao) {
        this.cartDao = cartDao;
        this.userDao = userDao;
    }

    @GetMapping("/myCarts")
    public String getMyCarts() {
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null) {
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null) {
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("uid", user.getId());
        List<Cart> carts = cartDao.findCart(map);
        logger.info("获取购物车成功---->" + carts);
        if (carts == null || carts.isEmpty()) {
            return PackJsn.pack(200, "购物车为空", null);
        }
        return PackJsn.pack(200, "购物车", carts);
    }

    @GetMapping("/deleteCart/{id}")
    public String deleteCart(@PathVariable("id") Integer id) {
        if (id == null) {
            return PackJsn.pack(203, "购物车商品异常");
        }
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null) {
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        String account = userDetails.getUsername();
        User user = userDao.findOneByAccount(account);
        if (user == null) {
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        Cart cart = new Cart();
        cart.setId(id);
        cart.setUid(user.getId());
        int i = cartDao.deleteCart(cart);
        Map<String, Object> map = new HashMap<>(1);
        map.put("uid", user.getId());
        List<Cart> carts = cartDao.findCart(map);
        if (i==0){
            return PackJsn.pack(203, "购物车商品异常",carts);
        }
        logger.info("删除购物车---->" + id);
        return PackJsn.pack(200, "删除成功", carts);
    }

    @PostMapping("/addCart")
    public String addCart(@RequestBody Cart cart) {
        logger.info("添加购物车---->" + cart);
        Object who = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (who == null) {
            logger.info("未登录无法获取用户信息");
            return PackJsn.pack(401, "未登录", null);
        }
        UserDetails userDetails = (UserDetails) who;
        String account = userDetails.getUsername();
        User user = null;

        user = userDao.findOneByAccount(account);

        if (user == null) {
            logger.info("未找到用户");
            return PackJsn.pack(401, "该用户不存在", null);
        }
        int i = 0;
        cart.setUid(user.getId());
        try {
            i = cartDao.addCart(cart);
        } catch (Exception e) {
            //如果报错，那么说明数据库已存在该用户提交的提交购物车（限制重复提交记录）
            return PackJsn.pack(200, "购物车中,已存在!!!");
        }
        if(i > 0){
            return PackJsn.pack(200, "已添加至购物车");
        }
        return PackJsn.pack(203, "添加购物车失败");
    }
}
